<template>
    <div class="container" v-loading.fullscreen.lock="loading" element-loading-text="加载中，请稍候...">
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item>系统设置</el-breadcrumb-item>
            <el-breadcrumb-item>资源设置</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="stu-header">
            <div class="stu-header-l">
                <el-select v-model="searchForm.sysCheckOptions" multiple placeholder="选择系统" style="width: 215px" @change="changeSearchName" filterable collapse-tags clearable>
                    <el-option v-for="item in systemList" :key="item['id']" :label="item['name']" :value="item['id']">
                        <el-checkbox v-model="item.isCheck" @click.prevent>{{item['name']}}</el-checkbox>
                    </el-option>
                </el-select>
            </div>
            <div class="stu-header-r">
                <el-button v-permission="'sys:func:getIconUrl'" @click="lookIconUrl">图标链接</el-button>
                <el-button v-permission="'sys:func:saveOrUpdate:1'" @click="addList()">新增资源</el-button>
                <el-button @click="openTable">展开/收起</el-button>
                <el-button v-permission="'sys:func:page'" class="el-icon-s-tools" @click="openListSetting"> 列配置</el-button>
            </div>          
        </div>
        <div class="cons">
            <el-table :data="dataList" style="width: 100%" ref="multipleTableRef" :row-key="row => row.id" @filter-change="tableFilterChange" :span-method="spanMethod">
                <template v-for="(c, i) in tableColumns" :key="i">                  
                    <el-table-column :prop="c.prop" :label='c.name' :fixed="c.f" :min-width="c.width" :show-overflow-tooltip="c.showOverflowTooltip"
                        :align="c.align" :header-align="c.headeralign" :column-key='c.columnKey' v-if="c.isShow && !c.customHeaderObj"
                        :filters="c.filters" :filter-multiple="c.filterMultiple" 
                    >
                        <template #default="scope">
                            <div v-if="dataListParam.length && !scope.row.id" class="searchTable-data">
                                搜索“
                                    <template v-for="(item,index) in dataListParam" :key="index">
                                        <span v-if="index!=0" :key="index+item.names">，</span>
                                        <span>{{item.labelName}}</span>：{{Array.isArray(item.names) ? item.names.join(',') : item.names}}
                                    </template>
                                ”，找到<span style="margin: 0 8px;">{{pagenation.totalPage}}</span>条结果 <el-button style="margin-left: 8px;" type="text" @click="clearSearchParam">清空筛选</el-button>
                            </div>
                            <template v-else-if="scope.row.id">
                                <template v-if="c.prop=='isShow' || (c.prop=='bi' && scope.row.type==2)">
                                    <el-tag type="danger" v-if="scope.row[c.prop]==1">否</el-tag><el-tag type="success" v-else-if="scope.row[c.prop]===0">是</el-tag>
                                </template>   
                                <template v-else-if="c.prop=='type'">
                                    <el-tag v-if="scope.row[c.prop]==1">菜单</el-tag>
                                    <el-tag v-else-if="scope.row[c.prop]==2" 
                                        style="border-color: rgb(188, 217, 239);color: rgb(52 148 225);background-color: rgb(207 233 255);">操作</el-tag>
                                    <el-tag v-else style="border-color: rgb(188, 217, 239);color: rgb(59 69 137);background-color: rgb(151 145 249 / 55%);">按钮</el-tag>
                                </template>   
                                <template v-else-if="(c.prop=='openType' || scope.row[c.prop]===0) && scope.row.type!=3">
                                    <el-tag type="info" v-if="c.prop=='openType' || scope.row[c.prop]===0">{{scope.row[c.prop]===0? '选项卡' : (scope.row[c.prop]==1 ? '浏览器' : '浏览器带菜单栏')}}</el-tag>
                                </template>  
                                <template v-else-if="((c.prop=='openType' || scope.row[c.prop]===0) && scope.row.type==3) || (c.prop=='bi' && scope.row.type!=2)"></template>  
                                <template v-else-if="c.prop=='iconCode'"><i :class="scope.row[c.prop]" style="color: #555555;" class="iconfont"></i></template>                      
                                <span v-else>{{scope.row[c.prop]}}</span>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column :key="c.prop" :prop="c.prop" :label='c.name' :fixed="c.f" :min-width="c.width" :show-overflow-tooltip="c.showOverflowTooltip"
                        :align="c.align" :header-align="c.headeralign" :column-key='c.columnKey' v-if="c.isShow && c.customHeaderObj"
                        :filters="c.filters" :filter-multiple="c.filterMultiple" 
                    >
                        <template #header="scope">
                            <FilterHeader :column="scope.column" :field-name="c.customHeaderObj && c.customHeaderObj['fieldName']" :filter-type="c.customHeaderObj && c.customHeaderObj['filterType']" 
                            :custom-arr-list="c.customHeaderObj && c.customHeaderObj['dictList']" @tableFilter="tableFilterConfirm" :searchForm="searchForm"
                            @resetFilter="tableFilterReset" />
                        </template> 
                    </el-table-column>
                </template> 
                <el-table-column prop="" label="" width="200" fixed="right">
                    <template #default="scope">
                        <template v-if="scope.row.id">
                            <el-button icon="Delete" type="text" size="small" title="删除" style="margin:0;padding:0;" v-permission="'sys:func:delete'" @click="handleDelete(scope.row)">删除</el-button>
                            <el-button icon="User" type="text" size="small" title="授权人员" style="margin:0;padding: 0 5px;" v-permission="'sys:func:authDetail'" v-if="scope.row.type !=1" @click="handleAuthStatus(scope.row)">授权人员</el-button>
                            <el-button icon="Edit" type="text" size="small" title="编辑" :style="scope.row.type==1? 'margin:0;padding: 0 5px;' : 'margin:0;padding: 0;'" v-permission="'sys:func:saveOrUpdate:2'" @click="addList('editor',scope.row)">编辑</el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    @size-change="sizeChangeHandle"
                    @current-change="currentChangeHandle"
                    :current-page="pagenation.pageIndex"
                    :page-sizes="[20,30,40,50,100]"
                    :page-size="pagenation.pageSize"
                    :total="pagenation.totalPage"
                    layout="total, sizes,prev, pager, next, jumper">
                </el-pagination>
            </div>
        </div>
        <!--新增资源 -->
        <el-dialog :title="addForm.title" v-loading="loading" v-dialogDrag v-set-dialog-height v-if="addFormVisible" v-model="addFormVisible" width="700px" :close-on-click-modal="false" append-to-body>
            <div class="el-dialog-div">
                <el-form :model="addForm" :inline="true" class="demo-form-inline" label-position="right" :rules="addFormRules" ref="addFormRulesRef" 
                    label-width="80px"
                >
                    <div>
                        <el-form-item class="header-title" label="系统" prop="systemId">
                            <el-select placeholder="请选择系统" size="medium" v-model="addForm.systemId" @change="switchSystem">
                                <el-option v-for="item in systemList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item class="header-title" label="类型" prop="type">
                            <el-select placeholder="请选择类型" size="medium" v-model="addForm.type" :disabled="addForm.editor" @change="switchSystem">
                                <el-option label="菜单" :value="1"></el-option>
                                <el-option label="操作" :value="2"></el-option>
                                <el-option label="按钮" :value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div>
                        <el-form-item class="header-title" label="名称" prop="name">
                            <el-input size="medium" v-model.trim="addForm.name"></el-input>
                        </el-form-item> 
                        <el-form-item class="header-title" label="上级资源" prop="parentId">
                            <!-- <el-select-tree v-model="addForm.parentId" filterable :multiple="false" :data="parentResourceList" @change="changeParentId(addForm.parentId)"
                                :props="{label: 'name',children: 'children'}"></el-select-tree> -->
                            <el-tree-select size="medium" v-model="addForm.parentId" :data="parentResourceList" :render-after-expand="false" check-strictly
                                :props="defaultProps" value-key="id" highlight-current></el-tree-select>
                        </el-form-item>
                    </div>
                    <div>
                        <el-form-item class="header-title" label="权限说明" prop="permissionExplain">
                            <el-input size="medium" v-model.trim="addForm.permissionExplain" clearable></el-input>
                        </el-form-item> 
                        <el-form-item class="header-title" label="标注" prop="tagged">
                            <el-input size="medium" v-model.trim="addForm.tagged" clearable></el-input>
                        </el-form-item>
                    </div>  
                    <div>
                        <el-form-item class="header-title" label="排序" prop="sort">
                            <div class="crm-sort-input">
                                <el-input-number size="medium" v-model="addForm.sort" :precision="0" controls-position="right" :min="1" :max="1000"></el-input-number>
                            </div>
                        </el-form-item> 
                        <el-form-item class="header-title" label="显示" prop="isShow">
                            <el-radio-group size="medium" v-model="addForm.isShow">
                                <el-radio :label="0">是</el-radio>
                                <el-radio :label="1">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>   
                    <div>
                        <el-form-item class="header-title" label="图标代码">
                            <el-input size="medium" v-model.trim="addForm.iconCode" placeholder="在线链接中图标代码"></el-input>
                        </el-form-item>
                        <el-form-item class="header-title" label="下钻(BI)">
                            <el-select placeholder="" size="medium" v-model="addForm.bi" clearable>
                                <el-option label="有" :value="1"></el-option>
                                <el-option label="无" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </div>                     
                    <div v-if="addForm.type==2 && addForm.bi ===1">                     
                        <el-form-item class="header-title" label="下钻页面">
                            <el-input size="medium"  v-model.trim="addForm.biPageId" placeholder="填写pageId" clearable></el-input>
                        </el-form-item>
                        <el-form-item class="header-title" label="下钻参数">
                            <el-input size="medium" v-model.trim="addForm.biParam" placeholder="" clearable></el-input>
                        </el-form-item>
                    </div>
                    <div v-if="addForm.type==2">
                        <el-form-item class="header-title single-long" label="资源地址">
                            <el-input size="medium" v-model.trim="addForm.location" placeholder="" clearable></el-input>
                        </el-form-item>                       
                    </div>  
                    <div>
                        <el-form-item class="header-title" label="打开方式" prop="openType" v-if="addForm.type!=3">
                            <el-radio-group v-model="addForm.openType">
                                <el-radio :label="0">选项卡</el-radio>
                                <el-radio :label="1">浏览器</el-radio>
                                <el-radio :label="2">浏览器带菜单栏</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item class="header-title" label="授权标识" v-if="addForm.type==3" prop="authKey">
                            <el-input size="medium" v-model.trim="addForm.authKey" placeholder=""></el-input>
                        </el-form-item>
                    </div> 
                    <div v-if="addForm.type!=3">
                        <el-form-item class="header-title" label="功能新旧" prop="ifNewFeature">
                            <el-select placeholder="" size="medium" v-model="addForm.ifNewFeature">
                                <el-option label="新" :value="1"></el-option>
                                <el-option label="旧" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </div>                 
                    <div>
                        <el-form-item class="header-title cj-dialog" label="备注" prop="remark">
                            <el-input type="textarea" class="text-input" v-model.trim="addForm.remark" maxlength="500" resize="none" rows="5" clearable></el-input>
                        </el-form-item>
                    </div>    
                </el-form>
            </div>
            <template #footer>
                <el-button @click="addFormVisible = false;">取 消</el-button>
                <el-button type="primary" @click="addFormSave()">确 定</el-button>       
            </template>
        </el-dialog>
        <!--图标链接 -->
        <el-dialog title="图标链接" v-dialogDrag v-if="iconUrlObj.iconUrlVisible" v-model="iconUrlObj.iconUrlVisible" width="480px" :close-on-click-modal="false" append-to-body>
            <div class="el-dialog-div">
                <el-form :model="iconUrlObj.form" :inline="true" class="demo-form-inline" label-position="right" label-width="78px">
                    <el-input v-model.trim="iconUrlObj.form.iconUrl"></el-input>
                </el-form>
            </div>
            <template #footer>
                <el-button @click="iconUrlObj.iconUrlVisible = false;">取 消</el-button>
                <el-button type="primary" @click="toSaveIconUrl">保 存</el-button>               
            </template>
        </el-dialog>
        <!-- 删除提示框 -->
        <el-dialog title="删除" v-model="delForm.delVisible" width="420px" v-if="delForm.delVisible" append-to-body>
            <template v-if="!delForm.delStatus">
                <div class="del-dialog-cnt">
                    <i class="el-message__icon el-icon-warning" style="color: #f56c6c;"></i>
                    <div>
                        <p>确定要删除<span style="color: #f56c6c;font-weight: 700;">{{delForm.form['name']}}</span>吗？</p>
                        <p>如果这么做, 已分配的角色中将连带删除该资源。该操作不能撤销。</p>
                    </div>
                </div>
              
            </template>
            <template v-else>
                <div class="del-dialog-cnt">
                    <template v-if="delForm.delFlag=='success'">
                        <i class="el-message__icon el-icon-success" style="color: #19bf24;"></i>
                        <div><p>成功</p></div>
                    </template>
                    <template v-if="delForm.delFlag=='error'">
                        <i class="el-message__icon el-icon-error" style="color: #f56c6c;"></i>
                        <div><p>{{delForm.delMsg}}</p></div>
                    </template>
                    
                </div>
               
            </template>
            <template #footer>
                <template v-if="!delForm.delStatus">
                    <el-button @click="delForm.delVisible = false">取 消</el-button>
                    <el-button type="primary" @click="deleteRow">确 定</el-button>
                </template>
                <template v-else>
                    <el-button @click="delForm.delVisible = false">关 闭</el-button>
                </template>
            </template>
        </el-dialog>
        <!-- 系统配置-授权情况 -->
        <el-dialog :title="`${authStatusList.name}-授权情况`" v-set-dialog-height v-model="authStatusVisible" width="660px" v-if="authStatusVisible" append-to-body>
            <div class="el-dialog-div" style="overflow: hidden;">
                <el-table :data="authStatusList.item" style="width: 100%;" highlight-current-row ref="authStatusRef" height="400">
                    <el-table-column prop="roleName" label='角色' header-align="left" align="left"></el-table-column>
                    <el-table-column prop="areaName" label='学区' header-align="left" align="left"></el-table-column>
                    <el-table-column prop="userName" label='用户' header-align="left" align="left"></el-table-column>
                    <el-table-column prop="masterJob" label='主副岗' header-align="center" align="center">
                        <template #default="scope">
                            <el-tag type="success" effect="dark" class="el-tag-circle" v-if="scope.row.masterJob==1">主</el-tag>
                            <el-tag type="warning" effect="dark" class="el-tag-circle" v-if="scope.row.masterJob==0">副</el-tag>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="auth-status-sum">
                    <span>汇总：共授权{{authStatusList.totalNum || 0}}人（{{authStatusList.masterJobNum || 0}}人主岗 {{authStatusList.assisJobNum || 0}}人副岗）</span>
                </div>
            </div>
            <template>
                <el-button type="primary" @click="authStatusVisible = false">关 闭</el-button>
            </template>
        </el-dialog>
        <!--列表配置 -->
        <el-dialog title="列表配置" v-dialogDrag v-if="listSettingVisible" v-model="listSettingVisible" width="480px" :close-on-click-modal="false" append-to-body>
            <div class="el-dialog-div">
                <p class="explan-tip">请选择需要在表格中显示的数据列</p>
                <el-form :model="addForm" :inline="true" class="demo-form-inline" label-position="right" label-width="78px">
                    <div class="list-setting-con">
                        <el-checkbox :indeterminate="isIndeterminate" class="check-all-only" v-model="columnsCheckAll" @change="handleColumnsCheckAllChange">全选</el-checkbox>
                        <div class="list-setting-border"></div>
                        <el-checkbox-group v-model="columnsCheckOptions" @change="handleCheckedColumnsChange">
                            <template v-for="(item,index) in columnList" :key="index">
                                <el-checkbox :title="item.name" :disabled="index==0 || index==1 || index==3" :label="item.prop" :value="item.prop">{{item.name}}</el-checkbox>
                            </template>
                        </el-checkbox-group>
                    </div>                    
                </el-form>
            </div>
            <template #footer>
                <el-button @click="listSettingVisible = false;">取 消</el-button>
                <el-button type="primary" @click="toListSetting">确 定</el-button>     
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import baseService from '@/service/baseService';
import { ArrowRight } from '@element-plus/icons-vue';
import useView from '@/hooks/useView';
import searchTableFilter from '@/hooks/searchTableFilter';
import { getCurrentInstance, nextTick, onActivated, onMounted, reactive, ref } from "vue";
import FilterHeader from '@/components/base/FilterHeader.vue';
// import ElSelectTree from '@/components/common/ElSelectTree.vue';
import { IObject} from "@/types/interface";
import { loadStyle } from '@/utils/loadStyle';
import useSaveFlag from '@/mixin/saveFlag';
import { onBeforeRouteLeave, useRoute } from 'vue-router';
    const { proxy } = getCurrentInstance() as any;
    const route = useRoute();
    const multipleTableRef = ref(null);
    const addFormRulesRef = ref(null);
    let searchForm: IObject = ref({
        name: '',
        sysCheckOptions:[],
        isShow: [],
    });
    let addForm = ref({
        systemId: "",
        title: '新增资源',
        type: 1,
        name: '',
        parentId: '一级菜单',
        permissionExplain: '',
        tagged: '',
        sort: 1,
        isShow: 0,
        iconUrl: '',
        iconCode: '',
        location: '',
        openType: 0,
        authKey: '',
        bi: 0,
        biPageId: '',
        biParam: '',
        remark: '',
        ifNewFeature: 1
    });
    let addFormVisible = ref(false);
    let delForm = ref({
        idx: '',
        delStatus: false,
        delFlag: '',
        delVisible: false,
        delMsg: '',
        title: '',
        form: {}
    });
    let defaultProps = {
        label: 'name',children: 'children',type: 'link' // 将type.text替换为type.link
    };
    let addFormRules= ref({
        name: [{ required: true, message: '请输入名称！', trigger: 'change' },],
        systemId: [{ required: true, message: '请选择系统！', trigger: 'change' },],
        type:  [{ required: true, message: '请选择类型！', trigger: 'change' },],
        parentId: [{ required: true, message: '请选择上级资源！', trigger: 'change' },],
        sort: [{ required: true, message: '请输入排序！', trigger: 'change' },],
        isShow: [{ required: true, message: '请选择显示！', trigger: 'change' },],
        openType: [{ required: true, message: '请选择打开方式！', trigger: 'change' },],
        authKey: [{required: true, message: '请输入授权标识！', trigger: 'change'}],
        ifNewFeature: [{required: true, message: '请选择功能新旧！', trigger: 'change'}],
    });
    let systemList = ref([]);
    let isShowList= ref([{value:0, text: '是', id: 0, name:'是'},{value: 1, text: '否', id: 1, name: '否'}]);
    let searchTableParam = ref({
        isShowList: isShowList.value,
    });
    let dataList = ref([]);
    let loading = ref(false);
    let tableColumns = ref([
        {'name': '名称', 'prop': 'name', 'f': false, 'align': 'left','headeralign':'left', 'columnKey': 'name', type: true,width: 140,showOverflowTooltip: true,
            customHeaderObj: {show: true, fieldName: 'name', filterType: 'text', 'isShow': false}},
        {'name': '图标', 'prop': 'iconCode', 'f': false, 'align': 'left','headeralign':'left','isShow': false, width: 100},
        {'name': '类型', 'prop': 'type', 'f': false, 'align': 'left','headeralign':'left','columnKey': 'type',
            // 'filters':[{'text':'菜单','value':'1'},{'text':'操作','value':'2'},{'text':'按钮','value':'3'},],'filterMultiple':true,'isShow': false
        },
        {'name': '系统', 'prop': 'systemName', 'f': false, 'align': 'left','headeralign':'left','isShow': false, width: 130, showOverflowTooltip: true},
        {'name': '标注', 'prop': 'tagged', 'f': false, 'align': 'left','headeralign':'left','isShow': false},
        {'name': '权限说明', 'prop': 'permissionExplain', 'f': false, 'align': 'left','headeralign':'left','isShow': false, width: 100, showOverflowTooltip: true},
        {'name': '排序', 'prop': 'sort', 'f': false, 'align': 'right','headeralign':'right','isShow': false},
        {'name': '打开方式', 'prop': 'openType', 'f': false, 'align': 'left', width: '100','headeralign':'left','isShow': false},
        {'name': '资源地址', 'prop': 'location', 'f': false, 'align': 'left','headeralign':'left','isShow': false,width: 100, showOverflowTooltip: true},
        {'name': '授权标识', 'prop': 'authKey', 'f': false, 'align': 'left','headeralign':'left','isShow': false, "showOverflowTooltip": true},
        {'name': '显示', 'prop': 'isShow', 'f': false, 'align': 'left','headeralign':'left','isShow': false,'filterMultiple':true,
            columnKey: 'isShow','filters':[{'text':'是','value':0},{'text':'否','value':1}],},
        {'name': '下钻(BI)', 'prop': 'bi', 'f': false, 'align': 'left','headeralign':'left','isShow': false},
        {'name': '备注', 'prop': 'remark', 'f': false, 'align': 'left','headeralign':'left','isShow': false, width: 110, showOverflowTooltip: true},
        {'name': '创建时间', 'prop': 'createTime', 'f': false, 'align': 'right','headeralign':'right','isShow': false, width: 160},
        {'name': '创建人', 'prop': 'createPerson', 'f': false, 'align': 'center','headeralign':'center','isShow': false},
        {'name': '最新修改日', 'prop': 'modifyTime', 'f': false, 'align': 'right','headeralign':'right','isShow': false, width: 140},
        {'name': '最新修改人', 'prop': 'modifyPerson', 'f': false, 'align': 'center','headeralign':'center','isShow': false, width: 110},
    ]);
    let columnsCheckAll= ref([]);
    let columnsCheckOptions= ref([]);
    let columnList= ref([{name: '名称', prop: 'name'},{name: '图标', prop: 'iconCode'},{name: '类型', prop: 'type'},{name: '系统', prop: 'systemName'},
        {name: '标注', prop: 'tagged'},{name: '权限说明', prop: 'permissionExplain'},{name: '排序', prop: 'sort'},{name: '打开方式', prop: 'openType'},
        {name: '资源地址', prop: 'location'},{name: '授权标识', prop: 'authKey'},{name: '显示', prop: 'isShow'},{name: '下钻(BI)', prop: 'bi'},
        {name: '备注', prop: 'remark'},{name: '创建时间', prop: 'createTime'},{name: '创建人', prop: 'createPerson'},{name: '修改时间一二三四五六七',prop: 'modifyTime'},
        {name: '最新修改人', prop: 'modifyPerson'},]);
    let isIndeterminate= ref(true);
    let showOpenTable= ref(false);
    let parentResourceList = ref([]);
    // let dataListParam = ref([]);
    let pagenation = ref({
        pageIndex: 1,
        pageSize: 20,
        totalPage: 0,
        loading: false
    });
    let addRowClick: IObject = {};
    let authStatusList: IObject= reactive({
        item: [],
        totalNum: '',
        masterJobNum: '',
        assisJobNum: ''
    });
    let authStatusVisible = ref(false);
    let iconUrlObj:IObject = reactive({//图标链接
        iconUrlVisible: false,
        form: { iconUrl: '' },
    });
    let listSettingVisible= ref(false);//列表设置弹框

    onMounted(() => {
        columnsCheckOptions.value=['name','iconCode','type','systemName','tagged','permissionExplain','sort','openType','location','authKey','isShow'];
        getSessionSearch();      
    });
    onActivated(() =>{
        if (route.meta.isUseCache == true) {
            
        }
        // 通过这个控制刷新
        route.meta.isUseCache = false;
    });
    onBeforeRouteLeave((to:any, from:any, next:any)=>{        
        to.meta.isUseCache = false;
        next();    
    });
    let getSessionSearch =()=>{
        getParentList();
        getSystemList();
        // initColumns();
    };
     /**
     * 表格筛选项 确定操作
     */
    let tableFilterConfirm=(data:any, reset:any)=>{
        let val= "";
        if(data.conditions && data.conditions[data.filterType]){
            val = data.conditions[data.filterType];
        }
        searchForm.value[data.fieldName] =val
        getDataListParam(val, data.label);
        getDataList('first');
    };
     /**
     * 表格筛选项 重置操作
     */
    let tableFilterReset=(data: any)=>{
        JSON.stringify(searchForm.value) != '{}' ? searchForm.value[data.fieldName]='' : '';
        JSON.stringify(dataListParam) !='[]' ? getDataListParam('', data.label): '';
        getDataList('first');
    };

    // 改变页显示条数
    let sizeChangeHandle =(val:any)=> {
        pagenation.value.pageSize = val;
        pagenation.value.pageIndex = 1;
        getDataList();
    };
    // 当前页
    let currentChangeHandle= (val: any)=> {
       pagenation.value.pageIndex = val;
       getDataList();
    };
    let getDataList = (key?: any, clear?: any)=>{
        if (key == "first") {
            pagenation.value.pageIndex = 1;
            pagenation.value.pageSize = 20;
        }           
        let param = {
            name: searchForm.value.name || '',
            pageNo: pagenation.value.pageIndex,
            pageSize: pagenation.value.pageSize,
        }  
        loading.value = true;    
        (searchForm.value.isShow && searchForm.value.isShow.length==1) ? param['isShow'] = searchForm.value.isShow.join(',') : ''; 
        searchForm.value.sysCheckOptions.length ? param['systemIds'] = searchForm.value.sysCheckOptions.join(',') : '';
        baseService.get(`/sys/func/page`, param).then(res=>{
            loading.value = false;
            if(res.code !=0){
                return proxy.$message.error(res.msg);
            }
            let datas = res.data || {};
            if(clear){
                dataList.value = [];
                proxy.$forceUpdate();
            }
            nextTick(()=>{
                pagenation.value.totalPage = datas.total || 0;
                dataList.value = datas.records || [];
                if(dataListParam.value.length){
                    if(datas.records.length){
                        (dataList.value[0] && dataList.value[0].id) ? dataList.value.unshift({}) : dataList.value.shift();
                    }else{
                        dataList.value = [{}];
                    }
                }
            })
        })
    };
    //表格查询项 和 功能查询项 筛选条件内容=============================开始
    /**
     * 筛选项 查询数据
     */
    let tableFilterChange = (filters)=>{
        let isShow='';
        if(filters['isShow'].length){
            isShow = filters['isShow'];
        }
        searchForm.value.isShow= isShow;
        getDataListParam(searchForm.value.isShow, '显示');
        getDataList('first')

    }
    //表格查询项 和 功能查询项 筛选条件内容=============================结束
    let initColumns = (key?:string)=>{
        tableColumns.value.forEach((item:any)=>{
            item['isShow'] = false;
        })
        columnsCheckOptions.value.forEach((item,index)=>{
            let findIndex = tableColumns.value.findIndex(items=> item == items.prop);
            if(findIndex>-1){
                tableColumns.value[findIndex]['isShow'] = true;
            }
        })
        proxy.$forceUpdate();
        if(key=='setting') return false;
        getDataList('first');
    }
    //获取上级资源列表
    let getParentList = ()=>{
        let param = {
            type: addForm.type,
            systemId: addForm.systemId || ''
        };
        baseService.get(`/sys/func/simpleList`,param).then((res: any) => {
            if(res.code !=0){
                return proxy.$message.error(res.msg);
            }
            parentResourceList.value = res.data || [];
        })
    }
    //获取系统列表
    let getSystemList = () => {
        baseService.get(`/base/sysList`).then((res: any) => {
            if(res.code!=0){
                return proxy.$message.error(res.msg);
            };
            systemList.value = res.data;
            searchTableParam.value['systemList'] = systemList.value;
            let findIndex = systemList.value.findIndex(item=>item.name.includes('CRM'));
            if(findIndex > -1){
                searchForm.value.sysCheckOptions = [systemList.value[findIndex].id];
                systemList.value[findIndex]['isCheck']= true;
                initColumns();
            }
        })
    }
    //图标链接
    let lookIconUrl = () => {
        
        baseService.get(`/sys/func/getIconUrl`).then(res=>{
            if(res.code !=0){
                return proxy.$message.error(res.msg);
            }
            let datas = res.data || '';
            iconUrlObj.form.iconUrl = datas;
            iconUrlObj.iconUrlVisible = true;
        })
    }
    /**
     * 更新图标链接
     */
    let toSaveIconUrl=()=>{
        let param ={
            iconUrl : iconUrlObj.form.iconUrl || ''
        };
        
        baseService.post(`/sys/func/addIconUrl`, param).then(res=>{
            if(res.code !=0){
                return proxy.$message.error(res.msg);
            }
            proxy.$message.success('更新成功！')
            loadStyle(iconUrlObj.form.iconUrl);
            iconUrlObj.iconUrlVisible = false;
        })
    };
    //清空综合查询条件
    let changeSearchName = (val:any) => {
        // console.log(searchForm.value.sysCheckOptions);
        systemList.value.forEach(item => {
            if (val.includes(item['id'])) {
                item.isCheck = true
            } else {
                item.isCheck = false
            }
        })
        getDataListParam(val, '系统');
        getDataList('first');
    };
    //新增/修改
    let addList = (key?:string, rows?:IObject) => {
        let row = {};
        if(rows){
            row = JSON.parse(JSON.stringify(rows));
        }
        if(addFormRulesRef.value){
            addFormRulesRef.value.resetFields();
        }
        if(!key){//新增
            addForm.value={
                systemId: '',
                title: '新增资源',
                type: 1,
                name: '',
                parentId: '一级菜单',
                permissionExplain: '',
                tagged: '',
                sort: 1,
                isShow: 0,
                iconUrl: '',
                iconCode: '',
                location: '',
                openType: 0,
                authKey: '',
                bi: 0,
                biPageId: '',
                biParam: '',
                remark: '',
                ifNewFeature: 1
            };
            //1、查询了一个随查询选中项赋值，2、查询了多个，赋综合管理
            //类型 type: 菜单1、操作2、按钮3
            if(JSON.stringify(addRowClick) != '{}'){
                if(addRowClick['type']==3){
                    addForm.value.parentId='';
                }else{
                    //1、列表选中的哪行，新增默认，无选中 非按钮默认“一级菜单”；2、查询一种
                    addForm.value.parentId = (addRowClick['id']==-1 ||  addRowClick['id']=='一级菜单') ? '一级菜单' : addRowClick['id'];
                }
                addForm.value.systemId = addRowClick.systemId ? addRowClick.systemId : '';
                if(addRowClick.type==1){
                    addForm.value.type=2;
                }else if(addRowClick.type==2){
                    addForm.value.type=3;
                }else if(addRowClick.type==3){
                    addForm.value.type= null;
                }
            }
        }else{//编辑
            addForm.value = row;
            // if(this.addRowClick['type']==3){
            //     this.addForm.parentId='';
            // }else{
            addForm.value.parentId = (addForm.value['parentId']==-1 ||  addForm.value['parentId']=='一级菜单') ? '一级菜单' : addForm.value['parentId'];
            // }
            addForm.value.editor = true;
            addForm.value.title = `修改-${row['name']}`;
        }
        getParentList();
        addFormVisible.value = true;
    };
    /**
     * 新增资源 保存
     */
    let addFormSave=()=>{
        console.log(addForm,'addForm===')
        addFormRulesRef.value.validate((valid) => {
            if(valid){
                firstSave();
            }else{
                return proxy.$message.error('请输入必填项!');
            }
        })
    };
     //新增保存操作
    let dialogAddSave=()=>{
        let addForms = JSON.parse(JSON.stringify(addForm.value));
        if(addForms.parentId=='一级菜单'){
            addForms.parentId = -1;
        }
        loading.value = true;
        saveData('post', '/sys/func/saveOrUpdate', addForms).then(res => {
            loading.value = false;
            let datas = res.data;
            if(datas.code!=0){
                return proxy.$message.error(datas.msg);
            }
            addFormVisible.value = false;
            proxy.$message.success('保存成功！');
            getDataList('first');
        }, err => {
            proxy.$message.error(err)
        });
    };       
    const { firstSave, saveData } = useSaveFlag(dialogAddSave);
    /**
     * 清空筛选
     */
    let clearSearchParam =()=>{
        searchForm.value = {};
        dataListParam.value=[];
        systemList.value.forEach(item=> item.isCheck=false);
        if(multipleTableRef.value){
            multipleTableRef.value.clearFilter();
        }
        setTimeout(()=>{
            nextTick(()=>{
                searchForm.value = { sysCheckOptions: [], isShow: ''};
                getDataList('first', 'clear');                   
            })
        }, 100)
    };  
    /**
     * 删除 
     */
    let handleDelete=(row)=>{
        delForm.value={
            idx: row.id,
            delStatus: false,
            delFlag: '',
            delVisible: true,
            delMsg: '',
            title: `删除-${row.name}` || '',
            form: row
        }
    };
    // 确认删除
    let deleteRow =()=>{        
        baseService.delete(`/sys/func/delete/${delForm.value.idx}`, { }).then(res=>{
            delForm.value.delVisible = false;
            delForm.value.delStatus = true;
            if(res.code !==0){
                delForm.value.delFlag = 'error';
                delForm.value.delMsg="";
                // proxy.$message.error(res.msg);
                return false;
            }
            delForm.value.delFlag = 'success';
            // this.$message.success('删除成功');
            getDataList('first');
        })
    };
    /**
     * 列设置    开始
     * */
    let handleColumnsCheckAllChange=(val)=> {
        let info = columnList.value.map(item=>item.prop);
        columnsCheckOptions.value = val ? info : ['name','iconCode','systemName'];
        isIndeterminate.value = false;
    };
    let handleCheckedColumnsChange=(value)=> {
        let checkedCount = value.length;
        columnsCheckAll.value = (checkedCount === columnList.value.length);
        isIndeterminate.value = checkedCount > 0 && checkedCount < columnList.value.length;
    };
    /**
     * 打开列设置
     *  */ 
    let openListSetting=()=>{
        // this.columnsCheckOptions=['id','name','type','tagged','permissionExplain','sort','openType','location','authKey','isShow'];
        handleCheckedColumnsChange(columnsCheckOptions.value);
        listSettingVisible.value = true;
    };
    let toListSetting=()=>{
        listSettingVisible.value = false;
        nextTick(()=>{
            initColumns('setting');
        })
    };
    /**
     * 列设置  ========= 结束
     * */
    //表格展开/收起
    let openTable=(val)=> {
        showOpenTable.value = !showOpenTable.value;
        nextTick(() => {
            handleArr(dataList.value, showOpenTable.value);
        });
    };
    let handleArr=(arr, flag)=> {
        arr.forEach(i => {
            multipleTableRef.value.toggleRowExpansion(i, flag);
            if (i.children!== undefined && i.children !== null) {
                handleArr(i.children, flag);
            }
        });
    };
    /**
     * 授权人员
     */
    let handleAuthStatus =(rows: IObject)=>{
        let row = JSON.parse(JSON.stringify(rows));
        loading.value = true;
        baseService.get(`/sys/func/authDetail/${row.id}`).then(res=>{
            loading.value = false;
            if(res.code !==0){
                proxy.$message.error(res.msg);
                return false;
            }
            let datas = res.data;
            authStatusList = datas;
            authStatusList['name']= row.name;
            authStatusVisible.value = true;
        })
    };
    let switchSystem =()=>{
        addForm.value.parentId = '一级菜单'
        getParentList();
    };
    /**
     * 上级资源 清除
     */
    let changeParentId=(val: any)=>{
        console.log(addForm.value.parentId,'===val')
        if(!val){
            addForm['parentId']= '一级菜单';
        }
    };  
    const { dataListParam, spanMethod, getDataListParam } = searchTableFilter( tableColumns, searchTableParam )

</script>
<style lang="scss" scoped>
.text-input{
    width: 80%;
}
.crm-sort-input{
    width: 215px;
    .el-input__inner{
        width: 130px;
    }
}
.stu-header{
    display: flex;
    flex-direction: row;
    align-items: self-end;
    justify-content: space-between;
    margin-top: 20px;
}
.cons{
    margin-top: 20px;
    .table-handle-btn{
        padding: 4px;
        font-size: 12px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    }
}
.el-dialog-div{
    // height: 320px;
    overflow-y: auto;
    overflow-x: hidden;
    .auth-status-sum{
        background: #f3f3f3;
        color: #181818;
        text-align: center;
        padding: 10px 0;
        border-top: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
    }
    .el-tag-circle{
        border-radius: 36%;
    }
}
.radio-tabs{
    // text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    width: 430px;
    // flex-shrink: 0;
}
.flod-btn{
    cursor: pointer;
    margin-left: 20px;
}
.list-setting-con{
    border: 1px solid #d7d7d7;
    border-radius: 10px;
    // padding: 18px;
    .list-setting-border{
        // margin: 15px 0;
        width: 100%;
        height: 1px; 
        background: #d7d7d7;
    }
    .check-all-only{//,.list-setting-con ::v-deep .el-checkbox-group
        padding: 8px;
    }
}
.explan-tip{
    margin-bottom: 30px;
}
.del-dialog-cnt{
    display: flex;
    flex-direction: row;
    i{
        font-size: 24px;
    }
    p{
        color: #666;
        line-height: 28px;
        font-size: 14px;
        margin-left: 6px;
    }
}
/* 展开表格自定义icon图标   开始 */
/* // 没有children的行隐藏展开按钮 */
:v-deep(.row-expand-cover .el-table__expand-icon) {
  visibility: hidden;
}

/* // 调整外层表格和内层表格行列一致对齐 */
:v-deep(.el-table__expanded-cell) {
  padding-top: 0px;
  padding-right: 0px;
  padding-bottom: 0px;
  border-right-width: 0px;
  border-bottom-width: 0px;
}

/* // 重写展开icon */
:v-deep(.el-table__expand-icon) {
/* //   height: 26px ; */
    line-height: 22px !important;
    transform: rotate(-90deg);
}
.el-table :v-deep(.el-icon-arrow-right::before) {
  font-size: 16px;
}
:v-deep(.el-table__expand-icon--expanded) {
    /* translate(4px, 6px)  */
    transform: rotate(0deg);
}
:v-deep(.el-table__expand-icon .el-icon-arrow-right::before) {
  font-family: "iconfont";
  content: '\eb89';
}
/* 展开表格自定义icon图标   结束 */
</style>
